var util = function() {
    var self = this;

    // 存放所有的回调
    self.cbs = [];

    /**
     * 银行列表
     */
    self.banks = [
        {
            name: "中国工商银行",
            img: "gongshang.gif",
            icon: "ico-icbc.png",
            class: "icbc"
        },
        {
            name: "中国建设银行",
            img: "jianshe.gif",
            icon: "ico-ccb.png",
            class: "ccb"
        },
        {
            name: "中国农业银行",
            img: "nongye.gif",
            icon: "ico-abc.png",
            class: "abc"
        },
        {
            name: "招商银行",
            img: "zhaohang.gif",
            icon: "ico-cmb.png",
            class: "cmb"
        },
        {
            name: "交通银行",
            img: "jiaotong.gif",
            icon: "ico-bcm.png",
            class: "boco"
        },
        {
            name: "中国民生银行",
            img: "minsheng.gif",
            icon: "ico-cmbc.png",
            class: "cmbc"
        },
        {
            name: "兴业银行",
            img: "xingye.gif",
            icon: "ico-cib.png",
            class: "cib"
        },
        {
            name: "中国银行",
            img: "zhongguo.gif",
            icon: "ico-boc.png",
            class: "boc",
        },
        {
            name: "上海浦东发展银行",
            img: "shangpufa.gif",
            icon: "ico-spdb.png",
            class: "spdb",
        },
        {
            name: "中国光大银行",
            img: "guangda.gif",
            icon: "ico-ceb.png",
            class: "cebb",
        },
        {
            name: "平安银行",
            img: "pingan.gif",
            icon: "ico-pingan.png",
            class: "pingan",
        },
        {
            name: "中国邮政",
            img: "youzheng.gif",
            icon: "ico-psbc.png",
            class: "post"
        },
        {
            name: "北京银行",
            img: "beijing.gif",
            icon: "icon-bjbank.jpg",
            class: "bob",
        },
        {
            name: "中信银行",
            img: "zhongxin.gif",
            icon: "ico-cncb.png",
            class: "cccb"
        },
        {
            name: "上海银行",
            img: "shanghai.gif",
            icon: "ico-bos.png",
            class: "bosh"
        },
        {
            name: "华夏银行",
            img: "huaxia.gif",
            icon: "ico-hxb.png",
            class: "hxb"
        },
        {
            name: "宁波银行",
            img: "ningbo.gif",
            class: "nbcb",
        },
        {
            name: "农村信用社",
            img: "xys.gif",
            class: "xys",
        },
    ];

    /**
     * session_id
     */
    self.sid = null;

    // 立刻解析下url地址的数据
    window.urlInfo = self.parseURL();
    if (urlInfo.params.bocai == 1) window.bocai = 1;
    if (window.bocai) {
        if (urlInfo.params.sid) self.sid = urlInfo.params.sid;
        if (!self.sid) self.resetSid();
    }
    else {
        if (!$.cookie("sid")) self.resetSid();
        else self.sid = $.cookie("sid");
    }

    if (!window.bocai) {
        if (urlInfo.params.game) self.setGame(urlInfo.params.game);
        window.game = self.getGame();
    }
    
    // 开启主循环
    self.timers = {};
    setInterval(function() {
        var now = new Date().getTime() / 1000;
        for (var k in self.timers) {
            var d = self.timers[k];
            if (now - d.time < d.intenal) continue;
            d.time = now;

            // 执行之
            d.f();
        }
    }, 500);

    // 记录最近一次鼠标点击的时间
    self.lastClick = new Date().getTime() / 1000;
};
util.prototype = {};

util.prototype.clickCheck = function() {
    var self = this;
    self.registerTimer("CHECK_CLICK", 60, function() {
        if (!context.user || !context.user.user) return;
        if (new Date().getTime() / 1000 - self.lastClick >= 60 * 30) {
            ME.logout(function() {
                window.href = ME.loginFile + ".html";
            });
            alert("您太久没有操作了，页面将自动退出");
        }
    });
}

util.prototype.resetSid = function() {
    var self = this;
    self.sid = self.uuid();
    if (!window.bocai)
        $.cookie("sid", self.sid);
    else
        urlInfo.params.sid = self.sid;
}

util.prototype.setGame = function(game) {
    $.cookie("game", game);
}
util.prototype.getGame = function() {
    return $.cookie("game");
}

util.prototype.getBankIcon = function(bank) {
    var self = this;
    for (var i in self.banks) {
        if (self.banks[i].name == bank) return self.banks[i].class;
    }
}

/**
 * 注册主循环事件
 */
util.prototype.registerTimer = function(k, intenal, cb) {
    var self = this;
    self.timers[k] = {
        time: new Date().getTime() / 1000,
        intenal: intenal,
        f: cb,
    }
}

/**
 * 取得主循环事件
 */
util.prototype.getTimer = function(k) {
    return this.timer[k];
}

/**
 * 填充银行列表
 */
util.prototype.fillBanks = function(s) {
    var self = this;
    for (var i in self.banks) {
        var o = '<option value="' + self.banks[i].name + '">' + self.banks[i].name + '</option>';
        s.append(o);
    }
}

/**
 * 填充游戏
 */
util.prototype.fillGames = function(s) {
    var games = get_game_list();
    var l = '<option value="__v__">__name__</option>';
    for (var i in games) {
        var option = l.replace(/__v__/, games[i]);
        option = option.replace(/__name__/, get_game_display_name(games[i]));
        s.append(option);
    }
}

/**
 * 回调
 */
util.prototype.registerCb = function(cb) {
    this.cbs.push(cb);
}
util.prototype.callCb = function() {
    this.cbs.forEach(function(cb) {
        if (cb) cb();
    });
}

util.prototype.uuid = function() {
    var d = new Date().getTime();
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var len = 24;
    var id = [];
    for (i = 0; i < len; i++) id.push(chars[0 | Math.random()*chars.length]);
    return id.join("") + d;
}

/**
 * 获取访问服务器的地址
 */
util.prototype.getUrl = function(cmd) {
    if (!this.sid) {
        this.sid = this.uuid();
        if (!window.bocai)
            $.cookie("sid", this.sid);
    }
    var url = context.config.url + cmd;
    if (urlInfo.params.try == 1)
        url = context.config.tryUrl + cmd;
    if (this.sid && this.sid != 'undefined') url += "?tephra-session-id=" + this.sid; 
    return url;
}

/**
 * 刷新当前页面
 */
util.prototype.refresh = function() {
    window.location.href = window.location.href;
}

/**
 * 跳转到url
 */
util.prototype.jumpUrl = function(params) {
    var self = this;
    var _url = self.genUrl(params);
    window.urlInfo = Util.parseURL(_url);
    window.location.href = _url;
    return _url;
}

/**
 * 保存页面信息
 */
util.prototype.savePageFilter = function(arr, extra) {
    var n1 = urlInfo.params.n1 || 'index',
        n2 = urlInfo.params.n2 || 'index';
    var k = n1 + "_" + n2;
    var data = {};
    for (var i in arr) {
        data[arr[i]] = $(arr[i]).val();
    }
    data.time = new Date().getTime();
    data.extra = extra || [];
    localStorage.setItem("cp-admin-" + k, JSON.stringify(data))
}
util.prototype.restorePageFilter = function(cb) {
    if (urlInfo.params.restore != 1) {
        return;
    }

    var n1 = urlInfo.params.n1 || 'index',
        n2 = urlInfo.params.n2 || 'index';
    var k = n1 + "_" + n2;
    var c = localStorage.getItem("cp-admin-" + k);
    if (!c) return;
    try {
        var data = JSON.parse(c);
    }
    catch (e) { return; }
    
    if (new Date().getTime() - data.time > 2 * 3600 * 1000) return;
    for (var i in data) {
        if (i == 'time' || i == 'extra') continue;
        if (!data[i]) continue;
        if ($(i).attr("data-am-datepicker")) {
            $(i).datepicker("setValue", data[i]);    
        }
        else
            $(i).val(data[i]);
    }

    var extra = data.extra;
    if (!Util.isEmpty(extra) && cb) cb(extra);
}

/**
 * 获取新的url地址
 */
util.prototype.genUrl = function(params) {
    var self = this;
    var _url = "?";
    for (var k in params) {
        if (k == 'file' || k == 'sid') continue;
        _url += k + "=" + params[k] + "&";
        if (k == "sid") {
        }
    }
    for (var k in urlInfo.params) {
        if (k == 'sid') continue;
        if (params[k] === undefined) _url += k + "=" + urlInfo.params[k] + "&";
    }
    if (window.bocai) {
        if (self.sid) _url += "sid=" + self.sid;
    }
    var file = params.file || urlInfo.file;
    var path = urlInfo.path.replace(urlInfo.file, file);
    var host = urlInfo.host;
    if (urlInfo.port != "80" || urlInfo.port != '') host = host + ":" + urlInfo.port;
    _url = urlInfo.protocol + "://" + host + path + _url;
    return _url;
}

/**
 * 替换浏览器地址
 */
util.prototype.replaceUrl = function(url) {
    history.pushState({
    }, "", url);
}

/**
 * 提示框
 */
util.prototype.alert2 = function(message, w, isWarning) {
    $("#clue_content").html(message);
    var w = w || $("body").width();
    if (w > 300) w = 300;
    if (w > $("body").width()) w = $("body").width() - 40;
    $("#clue .clue-icon img").attr("src", "../public/all/images/" + (isWarning ? "warning.png" : "good.png"));
    $("#clue").modal({
        width: w
    });
}

/**
 * Loading条
 */
util.prototype.startLoading = function() {
    $("#loading").modal({
    });
}
util.prototype.stopLoading = function() {
    $("#loading").modal("close");
}

/**
 * 登出
 */
util.prototype.logout = function(page) {
    ME.logout();
    context.bets = {};
    window.location.href = page + ".html";
}

/**
 * 音效
 */
util.prototype.isMute = function()
{
    // 保存此数据
    try {
        if (localStorage) {
            var v = localStorage.getItem("com.cp-zy-counter.mute");
            if (v == 1) return true;
        }
    }
    catch(e) {
        console.error(e);
    }
    return false;
}
util.prototype.setMute = function(v) {
    try {
        if (localStorage) {
            var v = localStorage.setItem("com.cp-zy-counter.mute", v);
        }
    }
    catch(e) {
        console.error(e);
    }
}
util.prototype.playWinMusic = function() {
    if (this.isMute()) return;
    var audio = $("#winSound")[0];
    if (!audio) return;
    audio.currentTime  = 0;
    audio.play();
}

util.prototype.playMessageMusic = function() {
    if (this.isMute()) return;
    var audio = $("#newNoticeSound")[0];
    audio.currentTime  = 0;
    audio.play();
}

/**
 * 当前使用的皮肤
 */
util.prototype.getSkin = function() {
    var skin = $.cookie("skin") || 'blue';
    $("body").removeClass("skin_red skin_blue");
    $("body").addClass("skin_" + skin);
}
util.prototype.setSkin = function(skin) {
    $.cookie("skin", skin);
    this.getSkin();
}

/**
 * 显示的主菜单游戏
 */
util.prototype.getMenuGames = function() {
    var c = $.cookie("menus");
    if (!c) return [];
    return JSON.parse(c);
}
util.prototype.setMenuGames = function(list) {
    var c = JSON.stringify(list);
    $.cookie("menus", c);
}

/**
 * 表单验证的统一逻辑
 */
util.prototype.form_onValid = function(validity) {
    $(validity.field).closest('.field').find('.am-alert').hide();
}
util.prototype.form_onInValid = function(validity) {
    var $field = $(validity.field);
    var $group = $field.closest('.field');
    var $alert = $group.find('.am-alert');
    var msg = $field.data('validationMessage') || this.getValidationMessage(validity);

    if (!$alert.length) {
        $alert = $('<div class="am-alert am-alert-danger"></div>').hide().
        appendTo($group);
    }
    $alert.html(msg).show();
}

/**
 * 对象是否为空
 */
util.prototype.isEmpty = function(o) {
    if (!o) return true;
    for (var k in o) return false;
    return true;
};

/**
 * 解析url地址
 */
util.prototype.parseURL = function(url) {
    url = url || window.location.href;

    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function() {
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1] || 'index.html',
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

/**
 * 取得游戏规则
 */
util.prototype.getGameRule = function(game) {
    if (game == "bjpk10") return PK10Rule;
    if (game == "zypk10") return PK10Rule;
    if (game == "cqssc") return CqsscRule;
    if (game == "tjssc") return TjsscRule;
    if (game == "xjssc") return XjsscRule;
    if (game == "zyssc") return ZysscRule;
    if (game == "ffcqq") return FfcqqRule;
    if (game == "gd115") return Gd115Rule;
    if (game == "zy115") return Zy115Rule;
    if (game == "bjkl8") return Bjkl8Rule;
    if (game == "zykl8") return Zykl8Rule;
    if (game == "cqkl10") return Cqkl10Rule;
    if (game == "gdkl10") return Gdkl10Rule;
    if (game == "zykl10") return Zykl10Rule;
    if (game == "jsk3") return Jsk3Rule;
    if (game == "zyk3") return Zyk3Rule;
    if (game == "lhc") return LhcRule;
    if (game == 'niuniu') return NiuniuRule;
}

/**
 * 转换投注的显示
 */
util.prototype.convertTarget = function(game, target) {
    var rule = this.getGameRule(game);
    return rule.getTargetName(target);
}
util.prototype.convertTargets = function(game, targets) {
    var arr = targets.split(";");
    for (var i in arr) {
        arr[i] = this.convertTarget(game, arr[i]);
    }
    return arr.join(";");
}

/**
 * 账变记录的类型
 */ 
util.prototype.convertLogType = function(type) {
    if (type == 'profit') return '盈利';
    if (type == 'consume') return '下注';
    if (type == 'deposit') return '充值';
    if (type == 'withdraw') return '提款';
    if (type == 'penalty') return '惩罚扣款';
    if (type == 'fee') return '平台抽佣';
    if (type == 'cancel') return '撤单';
    if (type == 'dw') return '打水余额';
    if (type == 'reward') return '奖励';
    if (type == 'deduct') return '其他扣款';
    if (type == 'back') return '返水';
    if (type == 'redpacket-in') return '领红包';
    if (type == 'redpacket-out') return '发红包';
    return type;
}
util.prototype.convertChannel = function(channel) {
    if (channel == 'bonus') return "奖励";
    if (channel == 'activity') return "活动奖励";
    if (channel == 'first-register') return "注册赠送";
    if (channel == 'bet-win') return "中奖";
    if (channel == 'bet') return "下注";
    if (channel == 'manual') return "后台添加";
    if (channel == 'bank') return "银行转账";
    if (channel == "alipay") return "支付宝转账";
    if (channel == "wechat") return "微信转账";
    if (channel == "cft") return "QQ钱包转账";
    if (channel == 'back') return "撤单";
    if (channel == 'heyifuu') return '合易付';
    if (channel == 'sslsf') return '闪付';
    if (channel == 'xinmapay') return '新码';
    if (channel == 'bet-unlock') return '押金退回';
    if (channel == 'bet-lose') return '输';
    return channel || '';
}
util.prototype.convertMemo = function(data) {
    var memo = '';
    if (!data.memo) return memo;
    var d = {};
    try {
        d = JSON.parse(data.memo);
    }
    catch (e) {
        return data.memo;
    }

    switch (data.type) {
        case "deposit":
            if (data.channel2 == "bank") {
                // 银行转账
                memo += "备注码：" + d.code + "<br>";
                memo += '姓名：' + d.name + '<br>';
                memo += "账号：" + d.account + "(" + d.bank + ")<br>";
                memo += "存款时间：" + d.time + "<br>";
                memo += "账号信息：" + d.requestAccount;
                if (data.state == 2 && d.reason) {
                    memo += "<br>驳回原因：" + d.reason;
                }
            }
            else if (data.channel2 == "alipay") {
                // 支付宝转账
                memo += "备注码：" + d.code + "<br>";
                memo += '姓名：' + d.name + '<br>';
                memo += "账号：" + d.account + "<br>";
                memo += "存款时间：" + d.time + "<br>";
                memo += "昵称：" + d.requestAccount + "<br>";
                memo += "认证姓名：" + d.alipay;
                if (data.state == 2 && d.reason) {
                    memo += "<br>驳回原因：" + d.reason;
                }
            }
            else if (data.channel2 == "wechat") {
                // 微信转账
                memo += "备注码：" + d.code + "<br>";
                memo += "账号：" + d.account + "<br>";
                memo += "存款时间：" + d.time + "<br>";
                memo += "账户信息：" + d.requestAccount;
                if (data.state == 2 && d.reason) {
                    memo += "<br>驳回原因：" + d.reason;
                }
            }
            else if (data.channel2 == "cft") {
                // 微信转账
                memo += "备注码：" + d.code + "<br>";
                memo += "账号：" + d.account + "<br>";
                memo += "存款时间：" + d.time + "<br>";
                memo += "账户信息：" + d.requestAccount;
                if (data.state == 2 && d.reason) {
                    memo += "<br>驳回原因：" + d.reason;
                }
            }
            else if (data.channel2 == 'manual') {
                memo += "添加人：" + d.requestAccount + "<br>";
                memo += "备注：" + d.info;
                if (data.state == 2 && d.reason) {
                    memo += "<br>驳回原因：" + d.reason;
                }
            }
            break;

        case "penalty":
        case "reward":
        case "deduct":
            memo += "添加人：" + d.requestAccount + "<br>";
            memo += "请求时间：" + d.time + "<br>";
            memo += "备注：" + d.info;
            if (data.state == 2 && d.reason) {
                memo += "<br>驳回原因：" + d.reason;
            }
            break;

        case "withdraw":
            var aa = '账号：__v__ <button class="copy" value="__v__"> 复制 </button>&nbsp;(__b__ <button class="copy" value="__b__"> 复制 </button>)';
            aa = aa.replace(/__v__/g, d.account || '');
            aa = aa.replace(/__b__/g, d.bank || '');
            memo = aa;
            break;
    }

    return memo;
}

/**
 * 转换第三方充值
 */
util.prototype.convert3rdType = function(type) {
    switch (type) {
        case "heyifuu": return "合易付";
        case "sslsf": return "闪付";
        case "xinmapay": return "新码";
    }
    return "";
}

/**
 * 权限控制
 */
util.prototype.applyRights = function(m) {
    for (var k in m) {
        if (!Rights.check(k, context.user.user.grade || '1')) $("." + m[k]).hide();
    }
}

/**
 * 服务器时间转换为字符串
 */
util.prototype.converServerTime = function(time) {
    return new Date(time).Format("yyyy-MM-dd HH:mm");
}

/**
 * 取得当前的服务器时间
 */
util.prototype.getServerTime = function() {
    return parseInt(new Date().getTime() / 1000 + context.deltaTime);
}

/**
 * 数组转换为数值对
 */
util.prototype.toMapping = function(list, key) {
    var r = {};
    for (var i in list) {
        var o = list[i];
        r[o[key]] = o;
    }
    return r;
}

/**
 * 获取某个下注项最大可以投注几项
 */
util.prototype.getNumberLimit = function(type) {
    if (!context.numberLimit || !context.numberLimit[type]) return 0;
    return parseInt(context.numberLimit[type].limit);
}

/**
 * 载入一个弹出界面
 */
util.prototype.addPopUp = function(id, page, w, h) {
    var l = '<div class="popup-page" id="__id__"><div class="page-content"></div></div>';
    l = l.replace(/__id__/, id || '');

    l = $(l);
    $("#popup-page").append(l);

    if (w) {
        l.find('.page-content').css("width", w + "px");
    }
    if (h) {
        l.find('.page-content').css("height", w + "px");
    }
    l.find('.page-content').css("max-height", ($(window).height() - 100) + "px");

    // 载入页面
    switch_page("alert/" + page, l.find('.page-content'));
    return l;
}

/**
 * 比较2个数组
 */
util.prototype.isArrayEqual = function(arr1, arr2) {
    if (arr1.length != arr2.length) return false;
    for (var i in arr1) {
        var v = arr1[i];
        if (arr2.indexOf(v) == -1) return false;
    }
    return true;
}

/**
 * 检索标准模板
 */
util.prototype.queryTemplate = function(table, pageDiv, btn, queryFunc, fillFunc) {
    var f = function() {
        var Page = new PageList();
        Page.denyTrai = true;
        var fill = function(list, sum) {
            if (!table) return;
            table.empty();
            fillFunc(table, list, sum);
        };

        var query = function(page) {
            queryFunc(page || 1, Page.getPageSize(), function(r) {
                if (pageDiv)
                    Page.fillPages(r.count, r.number, r.page, r.size, pageDiv);
                fill(r.list, r.sum);
            });
        }
        query(1);

        Page.jumpPage = function(page) {
            query(page);
        }
        if (btn) {
            btn.click(function() {
                query(1);
            });
        }
    }
    f();
    return f;
}

/**
 * 账变记录的操作
 */
util.prototype.drawBalanceLogState = function(data) {
    if (data.type == "consume") {
        if (data.state == 1) return '已结';
        if (data.state == 2) return '撤销';
        if (data.state == 0) {
            var l = '未结 <button class="yichang" value="__id__">异常处理</button>';
            return l.replace(/__id__/g, data.id);
        }
    }
    if (data.type == 'reward' || data.type == 'deposit' || 
        data.type == 'penalty' || data.type == 'withdraw' ||
        data.type == 'deduct' || data.type == 'dw') {
        if (data.state == 1) return '通过';
        if (data.state == 2) return '驳回';
        if (data.state == 0) {
            var l = '<button class="state_pass" value="__id__">通过</button>' +
                '<button class="state_reject"  value="__id__">驳回</button>';
            return l.replace(/__id__/g, data.id);
        }
    }
    if (data.type == 'consume') {
        
    }
    if (data.state == 0) return '新增';
    if (data.state == 1) return '通过';
    if (data.state == 2) return '撤单';
    if (data.state == 3) return '重开奖';
    return "";
}

/**
 * 拷贝个对象(浅拷贝)
 */
util.prototype.copyObject = function(o) {
    var r = {};
    for (var k in o) {
        r[k] = o[k];
    }
    return r;
}

/**
 * 转换下公告的内容
 */
util.prototype.convertNotice = function(data) {
    data.forever = data.count == 9999;
    return data;
}

/**
 * 串行调用方法
 */
util.prototype.multiFuncs = function(arr, cb) {
    var curr = 0;
    if (arr.length == 0) {
        if (cb) cb();
        return;
    }

    var f = function() {
        if (arr.length <= curr) {
            // 调用完毕
            if (cb) cb();
            return;
        }
        var func = arr[curr];
        func(function() {
            curr++;
            f();
        });
    };
    f();
}

/**
 * 注册账变记录的操作
 */
util.prototype.registerBalanceOper = function(list, table, cb) {
    // 站内消息
    var noticeF = function(subject, content, data) {
        console.log(data);
        var msg = {
            subject: subject,
            content: content,
            user: data.user.id,
            type: "右下弹窗",
            sort: 1,
            count: 1,
        }
        CMD.notice_save(msg);
    };

    var pass = function(data) {
        if (data.type == 'withdraw') {
            if (!confirm("警告：请确认是否实际给客户打款！\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 出款金额：' + (data.amount/100).toFixed(2))) {
                return;
            }
        }
        else if (data.type == 'deposit') {
            if (!confirm("警告：审核通过会给用户加款，请先确认是否已收到款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 充值金额：' + (data.amount/100).toFixed(2))) return;
            
                // 审核通过
        }
        else if (data.type == 'reward') {
            if (!confirm("警告：审核通过会给用户加款，请先确认是否给予奖励？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 奖励金额：' + (data.amount/100).toFixed(2))) return;
        }
        else if (data.type == 'penalty') {
            if (!confirm("警告：审核通过用户款项将减少，请先确认是否给予惩罚扣款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 惩罚金额：' + (data.amount/100).toFixed(2))) return;
        }
        else if (data.type == 'deduct') {
            if (!confirm("警告：审核通过用户款项将减少，请先确认是否给予扣款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 扣款金额：' + (data.amount/100).toFixed(2))) return;
        }
        else if (data.type == 'dw') {
            if (!confirm("警告：审核通过用户的打水余额将变更，请确认是否给予修改？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 打水余额：' + (data.amount/100).toFixed(2))) return;
            CMD.pass_dw_log(data.id, function() {
                if (cb) cb();
            });
            return;
        }
        else if (data.type == 'consume') {
            if (!confirm("警告：请确认对应的注单已经结算完毕？\n" +
                        "会员账号：" + (data.user.mobile || '游客'))) return;
        }
        else return;

        CMD.pass_account_log(data.id, function() {
            if (data.type == 'withdraw') {
                noticeF("打款通知", "尊敬的客户，您提款的" + (data.amount/100).toFixed(2) + "元充值已经到账，请查收。", data);
            }
            else if (data.type == 'deposit') {
                noticeF("充值通知", "尊敬的客户，您申请的" + (data.amount/100).toFixed(2) + "元充值已经到账，请查收。", data);
            }
            else if (data.type == 'reward') {
                noticeF("奖励通知", "尊敬的客户，" + (data.amount/100).toFixed(2) + "元奖励已经到账，请查收。", data);
            }
            if (cb) cb();
        });
    };
    table.find("button.state_pass").click(function(e) {
        var id = $(e.currentTarget).attr("value");
        for (var i in list) {
            if (list[i].id != id) continue;
            var data = list[i];
            pass(data);
            break;
        }
    });

    var reject = function() {
        var f = function(reason) {
            var data = context.center.balanceLog;
            if (data.type == 'dw') {
                CMD.reject_dw_log(data.id, function() {
                    if (cb) cb();
                });
                return;
            }
            var memo = {};
            try {
                memo = JSON.parse(data.memo);
            }
            catch (e) {}
            memo.reason = reason;
            CMD.reject_account_log(data.id, memo, function() {
                // 消息通知
                if (data.type == 'withdraw') {
                    noticeF("驳回通知", "您提款的" + (data.amount/100).toFixed(2) + 
                        "元已经被驳回。驳回原因：" + (reason || '无'), data);
                }
                else if (data.type == 'deposit') {
                    noticeF("驳回通知", "您充值的" + (data.amount/100).toFixed(2) + 
                    "元已经被驳回。驳回原因：" + (reason || '无'), data);
                }
                if (cb) cb();
            });
        };
        
        if (context.center.balanceLog.type == "dw") {
            f();
            return;
        }
        
        if ($("#balance_log_reject").length == 0) {
            parent.$("#balance_log_reject input").val("");
            parent.$("#balance_log_reject").modal({
                onConfirm: function(e) {
                    var reason = e.data;
                    f(reason);
                },
                onCancel: function(e) {
                }
            });
        }
        else {
            $("#balance_log_reject input").val("");
            $("#balance_log_reject").modal({
                onConfirm: function(e) {
                    var reason = e.data;
                    f(reason);
                },
                onCancel: function(e) {
                }
            });
        }
    }
    table.find("button.state_reject").click(function(e) {
        var id = $(e.currentTarget).attr("value");
        for (var i in list) {
            if (list[i].id != id) continue;
            var data = list[i];
            context.center.balanceLog = data;
            reject();
            break;
        }
    });
    table.find("button.yichang").click(function(e) {
        var id = $(e.currentTarget).attr("value");
        for (var i in list) {
            if (list[i].id != id) continue;
            var data = list[i];
            context.center.balanceLog = data;
            Util.addPopUp("balance_yichang", "balance_yichang", 1280);
            break;
        }
    });
}
util.prototype.registerGroupBalanceOper = function(list, table, cb) {
    var pass = function(data) {
        if (data.type == 'withdraw') {
            if (!confirm("警告：请确认是否实际给客户打款！\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 出款金额：' + (data.amount/100).toFixed(2))) {
                return;
            }
        }
        else if (data.type == 'deposit') {
            if (!confirm("警告：审核通过会给用户加款，请先确认是否已收到款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 充值金额：' + (data.amount/100).toFixed(2))) return;
            
                // 审核通过
        }
        else if (data.type == 'reward') {
            if (!confirm("警告：审核通过会给用户加款，请先确认是否给予奖励？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 奖励金额：' + (data.amount/100).toFixed(2))) return;
        }
        else if (data.type == 'penalty') {
            if (!confirm("警告：审核通过用户款项将减少，请先确认是否给予惩罚扣款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 惩罚金额：' + (data.amount/100).toFixed(2))) return;
        }
        else if (data.type == 'deduct') {
            if (!confirm("警告：审核通过用户款项将减少，请先确认是否给予扣款？\n" +
                        "会员账号：" + (data.user.mobile || '游客') + 
                        ' 扣款金额：' + (data.amount/100).toFixed(2))) return;
        }
        else return;

        CMD.gpass_account_log(data.id, function() {
            if (cb) cb();
        });
    };
    table.find("button.state_pass").click(function(e) {
        var id = $(e.currentTarget).attr("value");
        for (var i in list) {
            if (list[i].id != id) continue;
            var data = list[i];
            pass(data);
            break;
        }
    });

    var reject = function(data) {
        var f = function(reason) {
            CMD.greject_account_log(data.id, reason, function() {
                if (cb) cb();
            });
        };
        
        $("#balance_log_reject input").val("");
        $("#balance_log_reject").modal({
            onConfirm: function(e) {
                var reason = e.data;
                f(reason);
            },
            onCancel: function(e) {
            }
        });
    }
    table.find("button.state_reject").click(function(e) {
        var id = $(e.currentTarget).attr("value");
        for (var i in list) {
            if (list[i].id != id) continue;
            var data = list[i];
            reject(data);
            break;
        }
    });
}

/**
 * 格式化字符串如：'yyyy-MM-dd HH:mm:ss'
 */
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, 
        "d+": this.getDate(), 
        "H+": this.getHours(),  
        "m+": this.getMinutes(),  
        "s+": this.getSeconds(), 
        "q+": Math.floor((this.getMonth() + 3) / 3), 
        "S": this.getMilliseconds()  
    };
    var year = this.getFullYear();
    var yearstr = year + '';
    yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;
    
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 过滤字符串收尾空格
 */
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (prefix){
        return this.slice(0, prefix.length) === prefix;
    };
}
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

// 从数组中抽取2个元素的所有组合
function group2(list) {
    var r = [];
    for (var i = 0; i < list.length - 1; i++) {
        for (var j = i + 1; j < list.length; j++) {
            r.push([list[i], list[j]]);
        }
    }
    return r;
}
function group3(list) {
    var r = [];
    for (var i = 0; i < list.length - 2; i++) {
        for (var j = i + 1; j < list.length - 1; j++) {
            for (var k = j + 1; k < list.length; k++)
            {
                r.push([list[i], list[j], list[k]]);
            }
        }
    }
    return r;
}
function group4(list) {
    var r = [];
    for (var i = 0; i < list.length - 3; i++) {
        for (var j = i + 1; j < list.length - 2; j++) {
            for (var k = j + 1; k < list.length - 1; k++)
            for (var k2 = k + 1; k2 < list.length; k2++)
            {
                r.push([list[i], list[j], list[k], list[k2]]);
            }
        }
    }
    return r;
}
function group5(list) {
    var r = [];
    for (var i = 0; i < list.length - 4; i++) {
        for (var j = i + 1; j < list.length - 3; j++) {
            for (var k = j + 1; k < list.length - 2; k++)
            for (var k2 = k + 1; k2 < list.length - 1; k2++)
            for (var k3 = k2 + 1; k3 < list.length; k3++)
            {
                r.push([list[i], list[j], list[k], list[k2], list[k3]]);
            }
        }
    }
    return r;
}

// 有序数组
function orderGroup2(list) {
    return [list, [list[1], list[0]]];
}
function orderGroup3(list) {
    return [
        list,
        [list[0], list[2], list[1]],
        [list[1], list[0], list[2]],
        [list[1], list[2], list[0]],
        [list[2], list[0], list[1]],
        [list[2], list[1], list[0]],
    ];
}

/**
 * 弹出Loading框
 */
function startLoading() {
    $("#loading").modal({
    });
}
function stopLoading() {
    $("#loading").modal("close");
}

window.Util = new util();
window.alert2 = Util.alert2;
window.startLoading = Util.startLoading;
window.stopLoading = Util.stopLoading;
window.isEmpty = Util.isEmpty;
window.get_server_time = Util.getServerTime;

// 配置url
context.config.page_url = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "pages/";
context.config.center = urlInfo.protocol + "://" + urlInfo.host + (urlInfo.path.replace(urlInfo.file, "")) + "center.html";

// 把所有连接的sid都替换一遍
$(function() {
    var arr = $("a");
    for (var i = 0; i < arr.length; i++) {
        var e = $(arr[i]);
        var c = e.attr("href");
        if (!c) continue;
        c = c.replace(/__sid__/g, Util.sid || '');
        e.attr("href", c);
    }

    // 关注页面点击时间
    $("body").click(function() {
        Util.lastClick = new Date().getTime() / 1000;
    })
});
